<template>
  <el-dialog
    :visible="isShow"
    :title="mode === 'add' ? '新增角色' : '编辑角色'"
    width="35%"
    @close="closeEvent"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="角色介绍" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
    </el-form>
    <template>
      <div style="text-align: right">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="closeEvent">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { sysRolePost, sysRolePut } from '@/api/setting.js'
export default {
  name: '',
  model: {
    prop: 'isShow'
  },
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    },
    mode: {
      type: String,
      default: 'add'
    }
  },
  data: function() {
    return {
      initList: [],
      form: {
        //	string	必须		角色名称
        name: '',
        //	string	必须		角色描述
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let res = ''
              console.log('form', this.form)
              if (this.mode === 'add') {
                res = this.list.some((item) => item.name === value)
              } else {
                res = this.list.some(
                  (item) => item.name === value && item.id !== this.form.id
                )
              }
              res ? callback(new Error('重复名字')) : callback()
            }
          }
        ],
        description: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created() {
    // this.initList = JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    // 弹窗关闭时
    closeEvent() {
      this.$emit('input', false)
      // 清空表单/表单验证
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
      // this.form = JSON.parse(JSON.stringify(this.initList))
    },
    // 提交 : 新增/编辑
    submit() {
      this.$refs.form.validate(async(res) => {
        if (res) {
          if (this.mode === 'add') {
            await sysRolePost(this.form)
            this.$emit('currChange', 1)
          } else {
            await sysRolePut(this.form)
            this.$emit('getData')
          }
          this.closeEvent()
          this.$message.success(this.mode === 'add' ? '新增成功' : '修改成功')
        }
      })
    }
  }
}
</script>
<style scoped lang="scss"></style>
